package com.atguigu.spzx.sms.service.Impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.exception.GuiguException;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.sms.service.SmsService;
import com.atguigu.spzx.sms.util.HttpUtils;
import com.atguigu.spzx.util.RegexValidateUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author LT
 * @create 2024-03-26-20:39
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void sendMsg(String phone, Integer type) {
        if (type == null) {
            sendRegisterCode(phone);
        } else if (type.intValue() == 1) {

        } else if (type.intValue() == 2) {

        }
    }

    private void sendRegisterCode(String phone) {
        //
        boolean checkCellphone = RegexValidateUtils.checkCellphone(phone);
        if (!checkCellphone){
            throw new GuiguException(ResultCodeEnum.PHONE_ERROR);
        }
        if(stringRedisTemplate.hasKey("spzx:sms:count:"+phone)){
            throw new GuiguException(ResultCodeEnum.SEND_MSG_COUNT_ERROR);
        }
        String limitStr = stringRedisTemplate.opsForValue().get("spzx:sms:limit:" + phone);
        if (!StringUtils.isEmpty(limitStr) && Integer.parseInt(limitStr)>=25){
            throw new GuiguException(ResultCodeEnum.SEND_MSG_LIMIT_ERROR);
        }

        //------------------------------------------------------
        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = "bbf1f74b945c4b6dacaa3d7e8ee652e9";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        String code = RandomUtil.randomNumbers(4);
        querys.put("param", "**code**:"+code+",**minute**:5");
        System.out.println(code);

        //smsSignId（短信前缀）和templateId（短信模板），可登录国阳云控制台自助申请。参考文档：http://help.guoyangyun.com/Problem/Qm.html

        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
        Map<String, String> bodys = new HashMap<String, String>();


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从\r\n\t    \t* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java\r\n\t    \t* 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
//
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode!=200){
                throw new GuiguException(ResultCodeEnum.SEND_MSG_ERROR);
            }
//
            String result = EntityUtils.toString(response.getEntity());
            Map map = JSON.parseObject(result,Map.class);
            System.out.println(map.toString());
            if (!"成功".equals(map.get("msg"))){
                throw new GuiguException(ResultCodeEnum.SEND_MSG_ERROR);
            }
            stringRedisTemplate.opsForValue().set("spzx:sms:code"+phone,code,20, TimeUnit.MINUTES);
            stringRedisTemplate.opsForValue().set("spzx:sms:count:"+phone,"1",2,TimeUnit.MINUTES);
            Long limit = stringRedisTemplate.opsForValue().increment("spzx:sms:limit:"+phone);
            if (limit.longValue()==1){
                stringRedisTemplate.expire("spzx:sms:limit"+phone,1,TimeUnit.DAYS);
            }


        } catch (Exception e) {
            throw new GuiguException(ResultCodeEnum.SEND_MSG_ERROR);
        }
    }


}
